document.addEventListener('DOMContentLoaded', () => {
  // 切换标签页
  document.querySelectorAll('.tab-btn').forEach(button => {
    button.addEventListener('click', () => {
      document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
      
      button.classList.add('active');
      document.getElementById(button.dataset.tab).classList.add('active');
      loadResources();
    });
  });

  // 加载资源
  function loadResources() {
    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
      chrome.tabs.sendMessage(tabs[0].id, {action: 'getResources'}, resources => {
        updateResourceList(resources);
      });
    });
  }

  // 更新资源列表
  function updateResourceList(resources) {
    Object.keys(resources).forEach(type => {
      const container = document.querySelector(`#${type} .resource-list`);
      container.innerHTML = '';
      
      resources[type].forEach(url => {
        const item = document.createElement('div');
        item.className = 'resource-item';
        
        if (type === 'image') {
          const preview = document.createElement('img');
          preview.src = url;
          preview.className = 'resource-preview';
          item.appendChild(preview);
        }
        
        const link = document.createElement('a');
        link.href = url;
        link.textContent = url.split('/').pop();
        link.addEventListener('click', (e) => {
          e.preventDefault();
          chrome.downloads.download({url: url});
        });
        
        item.appendChild(link);
        container.appendChild(item);
      });
    });
  }

  // 下载全部按钮
  document.querySelectorAll('.download-all').forEach(button => {
    button.addEventListener('click', () => {
      const type = button.parentElement.id;
      chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.sendMessage(tabs[0].id, {action: 'getResources'}, resources => {
          resources[type].forEach(url => {
            chrome.downloads.download({url: url});
          });
        });
      });
    });
  });

  // 初始加载
  loadResources();
});